﻿namespace MicroCloud.Identity.Database
{
    /// <summary>
    /// 用户种子数据初始值设定项
    /// </summary>
    public class UserSeedDataInitializer : SeedDataInitializerBase<User, long>
    {
        /// <summary>
        /// 初始化一个用户种子数据初始值设定项（<see cref="UserSeedDataInitializer"/>）的新实例
        /// </summary>
        /// <param name="rootProvider"></param>
        public UserSeedDataInitializer(IServiceProvider rootProvider)
            : base(rootProvider)
        { }

        /// <summary>
        /// 重写以提供要初始化的种子数据
        /// </summary>
        /// <param name="provider">服务提供者</param>
        /// <returns></returns>
        protected override User[] SeedData(IServiceProvider provider)
        {
            return new[]
            {
                new User(){
                    UserName = "admin",
                    PasswordHash = "admin@123",//("").ToMD5(),
                    NickName = "超级管理员",
                    Email = "527068300@qq.com",
                    PhoneNumber = "15150420868"
                }
            };
        }

        /// <summary>
        /// 重写以提供判断某个实体是否存在的表达式
        /// </summary>
        /// <param name="entity">要判断的实体</param>
        /// <returns></returns>
        protected override Expression<Func<User, bool>> ExistingExpression(User entity)
        {
            return m => m.UserName.Equals(entity.UserName) && m.IsSystem;
        }

        /// <summary>
        /// 将种子数据初始化到数据库
        /// </summary>
        /// <param name="entities">实体对象数组</param>
        /// <param name="provider">服务提供者</param>
        protected override void SyncToDatabase(User[] entities, IServiceProvider provider)
        {
            if (entities == null || entities.Length == 0)
            {
                return;
            }

            provider.BeginUnitOfWorkTransaction(provider =>
            {
                var identityContract = provider.GetService<IIdentityContract>();
                foreach (var entity in entities)
                {
                    RegisterDto dto = new()
                    {
                        UserName = entity.UserName,
                        NickName = entity.NickName,
                        Password = entity.PasswordHash,
                        ConfirmPassword = entity.PasswordHash,
                        Email = entity.Email,
                        PhoneNumber = entity.PhoneNumber,
                        RegisterIp = string.Empty
                    };
                    var result = identityContract.Register(UserRegisterType.Neither, dto).Result;
                }
            });
        }
    }
}
